import Taro, { Component } from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'
import { connect } from '@tarojs/redux'
import { FormattedMessage} from 'react-intl'
//import './index.scss'

import { add, minus, asyncAdd } from './action'

@connect(({ counter }) => ({
  counter
}), (dispatch) => ({
  add () {
    dispatch(add())
  },
  dec () {
    dispatch(minus())
  },
  asyncAdd () {
    dispatch(asyncAdd())
  }
}))
export default class Counter extends Component {
  config = {
    navigationBarTitleText: '首页'
  }
  non_str = () => {
    let data = ''
    const chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    chars.forEach((i) => {
      let id = parseInt(Math.random() * (chars.length - 1))
      data += chars[id]
    })
    return data
  }

  payHandler = () => {
    Taro.requestPayment({
      timeStamp: Date.parse(new Date()),
      nonceStr: this.non_str(),
      package: `prepay_id=${prepay_id}`,
      signType: 'MD5',
      paySign: sign,
      async success(res) {
        Taro.showLoading({
          title: '正在支付',
        });

        Taro.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 1500,
          async success() {
            _this.getOrder();

            await wx.cloud.callFunction({
              name: 'pay',
              data: {
                type: 'payorder',
                data: {
                  body,
                  prepay_id,
                  out_trade_no,
                  total_fee
                }
              }
            });
            Taro.hideLoading();
          }
        });
      },
      fail: function (res) { }
    })
  }

  render () {
    return (
      <View className='todo'>
        <Button className='add_btn' onClick={this.props.add}>+</Button>
        <Button className='dec_btn' onClick={this.props.dec}>-</Button>
        <Button className='dec_btn' onClick={this.props.asyncAdd}>
          {/*<FormattedMessage
            id='async'
            defaultValue='Async'
            values={{async: 'ASYNC'}}
          />*/}

          async</Button>
        <View onClick={this.payHandler.bind(this)}>pay</View>
        <View>{this.props.counter.num}</View>
      </View>
    )
  }
}
